package su.mysrpingbootprojects.hibernatedemo;

import jakarta.annotation.PostConstruct;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
 * Класс StudentRepository
 * <p/>
 * Репозиторий нашего тестового проекта
 * <p/>
 *
 * @author petr.mikhailin
 * created 10.05.2024 16:08
 */
@Repository
@Transactional
public class StudentRepository {

    private SessionFactory sessionFactory;

    private final ApplicationContext applicationContext;

    @Autowired
    public StudentRepository(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    private void initSessionFactory() throws IOException {
        Configuration configuration = new Configuration();
        Properties properties = new Properties();
        properties.load(Objects.requireNonNull(
                applicationContext.getClassLoader()).getResourceAsStream("application.properties"));
        configuration.setProperties(properties);
        configuration.addAnnotatedClass(Student.class);
        sessionFactory = configuration.buildSessionFactory();
    }

    public void addNewStudent(Student student) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(student);
        transaction.commit();
        session.close();
    }

    public List<Student> getAllStudents() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        List<Student> studentList = session.createQuery("FROM Student").list();
        transaction.commit();
        session.close();
        return studentList;
    }

}